package com.hqyj.finance.server.users.financeusers.controller;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.hqyj.finance.server.users.financeusers.entity.Roles;
import com.hqyj.finance.server.users.financeusers.entity.Users;
import com.hqyj.finance.server.users.financeusers.json.R;
import com.hqyj.finance.server.users.financeusers.service.UsersRolesService;
import com.hqyj.finance.server.users.financeusers.service.UsersService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
//@RequestMapping("users")
public class UsersController extends BaseController {

    @Resource
    private UsersService usersService;
    @Resource
    private UsersRolesService usersRolesService;

    //查询所有的用户资料
    @GetMapping("/")
    public R queryAllUserList(){
        try{
            List<Users> usersList = usersService.queryAllUsers();
            return R.success("查询所有用户资料成功！",usersList);
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @PostMapping("reg")
    public R reg(@RequestBody Users u) {
        System.out.println("-----------执行了UsersController---------------");
        System.out.println(u);

        try {
            if (usersService.reg(u)) {
                return R.success("注册成功！");
            }
            return R.fail("注册失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("checkIsReg")
    public R checkIdentifyIsReg(@RequestParam(value = "identify", required = true) String identify) {
        try {
            if (usersService.checkIdentifyIsReg(identify)) {
                return R.fail("该手机或者电子邮箱已经被注册!");
            }
            return R.success("该手机或者邮箱可以注册！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("auth")
    public R login(@RequestParam("identify") String identify, @RequestParam("password") String password, @RequestParam("token") String token, @RequestParam("code") String code, HttpServletResponse response) {
        try {
            //首先检查验证码是否正确
            if(!redisUtil.hasKey(token)){
                //没有这个key
                return R.error("验证码不正确！");
            }

            String sessionRadomCode = (String) redisUtil.get(token);
            if(!code.equalsIgnoreCase(sessionRadomCode)){
                return R.error("验证码不正确！");
            }

            Users loginSuccessUser = usersService.login(identify, password);
            if (loginSuccessUser != null) {
                loginSuccessUser.setPassword("");
                //保存登录状态。
                StpUtil.login(loginSuccessUser.getUid(),new SaLoginModel().setIsLastingCookie(true).setTimeout(60*60*24*30));
                return R.success("登录成功！", loginSuccessUser);
            }
            return R.fail("登录失败，请检查用户名或者密码是否正确!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }

    }

    @GetMapping("isLogin")
    public R isLogin() {
        System.out.println("-----------前端发送了检查登录状态的请求--------------");
        Users loginSuccessUser = null;
        try {
            if (StpUtil.isLogin()) {
                System.out.println("已登录....");

                Object loginIdObj =StpUtil.getLoginId();
                loginSuccessUser = usersService.getById(Integer.parseInt(loginIdObj.toString()));
                List<Roles> rolesList = usersRolesService.queryUserRolesListByUid(Integer.parseInt(loginIdObj.toString()));
                List<String> list = new ArrayList<String>();
                if (rolesList != null && rolesList.size() > 0) {
                    for (Roles roles : rolesList) {
                        list.add(roles.getRoleName());
                        //list.add(roles.getRoleName());
                    }
                }
                loginSuccessUser.setRoles(list);
                loginSuccessUser.setPassword("");
                return R.success("已登录",loginSuccessUser);
            } else {
                System.out.println("未登录....");
                return R.fail("当前用户未登录");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("logout")
    public R logout() {
        try {
            StpUtil.logout();
            return R.success("注销成功！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @PutMapping("/update")
    public R updateUserProfile(@RequestBody Users user) {
        try {
            if (usersService.updateUsersProfile(user)) {
                return R.success("更新用户资料成功！");
            }
            return R.fail("更新用户资料失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    //获取登录用户的最新的资料
    @GetMapping("/profile")
    public R queryLoginUserProfile(@RequestParam("uid") Integer uid){
        try{
            System.out.println("UsersController==>queryLoginUserProfile():" + uid);
            Users loginUserProfile = usersService.queryUserProfileByUid(uid);
            if(loginUserProfile !=null){
                List<Roles> rolesList = usersRolesService.queryUserRolesListByUid(Integer.parseInt(loginUserProfile.getUid().toString()));
                loginUserProfile.setRolesList(rolesList);
                return R.success("查询最新用户资料成功！",loginUserProfile);

            }
            return R.fail("查询最新用户资料失败，该用户不存在！");
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }
}
